package com.nl.lib_core.tool.coroutines.extension

import com.nl.lib_core.tool.coroutines.convert
import com.nl.lib_core.tool.coroutines.uiScope
import kotlinx.coroutines.*

/**
 * 作者: wangfei 创建时间: 2021/12/27 包名: com.nl.lib_core.tool.coroutines.extension 类名: DeferredExtension
 */
infix fun <T> Deferred<T>.then(block: (T) -> Unit) = uiScope().launch { block(this@then.await()) }

infix fun <T, R> Deferred<T>.thenAsync(block: convert<T, R>) =
    uiScope().async { block(this@thenAsync.await()) }

suspend fun <T> Deferred<T>.awaitOrNull(timeOut: Long = 0L) =
    try {
      if (timeOut > 0) {
        withTimeout(timeOut) { this@awaitOrNull.await() }
      } else {
        this.await()
      }
    } catch (e: Exception) {
      System.err.println(e.message)
      null
    }

suspend inline fun <T, R> Deferred<T>.map(noinline convert: convert<T, R>): Deferred<R> =
    coroutineScope {
  async { convert(this@map.await()) }
}
